package com.starblink.discover.ui

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.android.basic.ext.bindProductFeeds
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.LikePostEvent
import com.starblink.android.common.adapter.cell.DiscoverPostCardCell
import com.starblink.android.common.databinding.ItemPostBannerBinding
import com.starblink.android.common.view.post.PostBannerHolder
import com.starblink.basic.autosize.utils.AutoSizeUtils
import com.starblink.basic.ext.screenHeight
import com.starblink.basic.route.RoutePage
import com.starblink.discover.cell.PostStarCardCell
import com.starblink.discover.util.ScrollCalculatorHelper2
import com.starblink.home.databinding.FragmentNavDiscoverBinding
import com.starblink.home.databinding.ItemPostStarCardBinding
import com.starblink.rocketreserver.fragment.PostF


class NavDiscoverFragment :
    BaseTVMFragment<FragmentNavDiscoverBinding, NavDiscoverVM>() {

    var layoutManager: StaggeredGridLayoutManager? = null

    companion object {
        fun obtainFragment(): NavDiscoverFragment {
            return NavDiscoverFragment()
        }
    }

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.mList.value!!).apply {
            addVhDelegate {
                DiscoverPostCardCell(
                    parent = it,
                    postList = viewModel.postList, spmPageValue = SpmPageDef.RecommendPage
                ) {
//                    if (viewModel.mLoadActionLiveData.value != LoadAction(LoadAction.STATE_LOADING))
                    viewModel.getRecommendPost()
                }
            }
            addVhDelegate {
                PostStarCardCell(
                    activity,
                    ItemPostStarCardBinding.inflate(it.inflater, it, false),
                )
            }
            addVhDelegate {
                PostBannerHolder(
                    activity, viewModel.mList.value!!,
                    ItemPostBannerBinding.inflate(it.inflater, it, false),
                )
            }
        }
    }

    @SuppressLint("ResourceAsColor")
    override fun initData() {
        pageExposure(SpmPageDef.RecommendPage)
        showStateLoading()

        viewModel.getRecommendPost(initData = true)

        layoutManager =
            viewBinding.rvDiscover.bindProductFeeds(
                adapter,
                horGap = 9, withEdge = true,
            ) as StaggeredGridLayoutManager?

        viewBinding.refresher.setOnRefreshListener {
            viewModel.getRecommendPost(initData = true)
            viewBinding.refresher.finishLoadMore(5000)
        }
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.getRecommendPost()
            viewBinding.refresher.finishLoadMore(5000)
        }

        autoPlayPostVideo2(
            mActivity,
            layoutManager,
            viewBinding.rvDiscover,
            com.starblink.android.common.R.id.video_player
        )

        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
//            if (it) {
//                viewModel.getRecommendPost(initData = true)
//            }
        }

        //同步点赞数据
        FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT).register(this) {
            if (it.postId != null) {
                for ((index, post) in viewModel.mList.value!!.withIndex()) {
                    if (post != null && post is PostF && it.postId == post.id && it.like != post.liked) {
                        ApolloValSetExt.setApolloVal<PostF>(post, "liked", it.like)
                        ApolloValSetExt.setApolloVal<PostF>(post, "likeNumbers", it.likeCount)
                        adapter.notifyItemChanged(index)
                        break
                    }
                }
            }
        }
        viewBinding.ivSearch.run {
            trackData(
                page = SpmPageDef.RecommendPage,
                element = SpmElementDef.DiscoverSearch, onlyHit = true
            )
            click {
                navigationTo(RoutePage.Search.PAGE_SEARCH) {
                    extraOf(RoutePage.Search.ARG_SCENE to RoutePage.Search.SCENE.DISCOVER.value)
                }
//                navigationTo(RoutePage.Post.PAGE_TOPIC) {
//                    withString(RoutePage.Post.TOPIC_ID, "594")
//                }
//                CommonRoute.startProductDetail(
//                    "b414ca1bf487a8d4c2f4e1e8c6169572",
//                    "b414ca1bf487a8d4c2f4e1e8c6169572",
//                    null
//                )
            }
        }
    }

    override fun startObserve() {
        viewModel.mList.observe(this) {
            showStateSuccess()
            if (viewModel.mList.value != null && viewBinding.rvDiscover.adapter == null) {
                viewBinding.rvDiscover.adapter = adapter
            }
            if (viewModel.mList.value != null && viewModel.mList.value!!.isNotEmpty()) {
                // 首页列表项应有数量
                val firstPageItemCount = viewModel.pageSize +
                        (if (viewModel.hasBanner) 1 else 0) +
                        (if (viewModel.starCardNum > 0) viewModel.starCardNum else 0)
                if (viewModel.mList.value!!.size == 1 && viewModel.hasBanner) {
                    // Banner加载完成，刷新列表
                    adapter.notifyDataSetChanged()
                } else if (viewModel.mList.value!!.size <= firstPageItemCount) {
                    // 首页刷新
                    adapter.notifyDataSetChanged()
                    viewModel.pageNo += 1
                } else {
                    // 加载更多
                    adapter.notifyItemRangeChanged(
                        viewModel.pageSize * viewModel.pageNo
                                + (if (viewModel.hasBanner) 1 else 0)
                                + (if (viewModel.starCardNum > 0) viewModel.starCardNum else 0),
                        viewModel.pageSize
                    )
                    viewModel.pageNo += 1
                }
            }
            if (viewBinding.refresher.isRefreshing) {
                viewBinding.refresher.finishRefresh()
            }
            if (viewBinding.refresher.isLoading) {
                viewBinding.refresher.finishLoadMore()
            }
        }

//        viewModel.bannerLD.observe(this) {
//            if (it?.isNotEmpty() == true) {
//
//                val previousSize: Int = viewModel.adapterList.size
//                if (previousSize > 0) {//避免当RecyclerView遇到Inconsistency detected崩溃
//                    viewModel.adapterList.clear()
//                    adapter.notifyItemRangeRemoved(0, previousSize)
//                }
//
//                viewModel.adapterList.add(0, it)
//                adapter.notifyItemRangeChanged(0, 1)
//            }
//        }
//        viewModel.recommendLD.observe(this) {
//            if (it.isEmpty()) {
//                viewBinding.refresher.finishLoadMoreWithNoMoreData()
//            } else {
//                viewModel.adapterList.addAll(it)
//                adapter.notifyItemRangeChanged(viewModel.adapterList.size - 1, it.size)
//                viewModel.pageNo += 1
//            }
//            if (viewBinding.refresher.isRefreshing) {
//                viewBinding.refresher.finishRefresh()
//            }
//            if (viewBinding.refresher.isLoading) {
//                viewBinding.refresher.finishLoadMore()
//            }
//        }
    }

    /**
     * 自动播放内容卡片视频
     */
    fun autoPlayPostVideo2(
        context: FragmentActivity,
        layoutManager: StaggeredGridLayoutManager?,
        rv: RecyclerView,
        viewId: Int
    ) {
        //限定范围为屏幕一半的上下偏移200
        val playTop = screenHeight / 2 - AutoSizeUtils.dp2px(200f)
        val playBottom = screenHeight / 2 + AutoSizeUtils.dp2px(200f)
        //自动播放帮助类
        var scrollCalculatorHelper =
            ScrollCalculatorHelper2(
                context,
                lifecycle,
                viewId,
                playTop,
                playBottom
            )

        rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var firstVisibleItem = 0
            var lastVisibleItem = 0
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                scrollCalculatorHelper.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val positions =
                    layoutManager!!.findFirstVisibleItemPositions(null)
                if (positions != null && positions.isNotEmpty()) {
                    firstVisibleItem = positions[0]
                }
                val positions2 =
                    layoutManager!!.findLastVisibleItemPositions(null)
                if (positions2 != null && positions2.isNotEmpty()) {
                    lastVisibleItem = positions2[positions2.size - 1]
                }

                //这是滑动自动播放的代码
                scrollCalculatorHelper.onScroll(
                    recyclerView,
                    firstVisibleItem,
                    lastVisibleItem,
                    lastVisibleItem - firstVisibleItem
                )
            }
        })
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentNavDiscoverBinding {
        return FragmentNavDiscoverBinding.inflate(inflater, container, false)
    }

}